<?php
App::uses('AppController', 'Controller');
/**
 * Tickets Controller
 *
 * @property Ticket $Ticket
 * @property PaginatorComponent $Paginator
 */
class TicketsController extends AppController {

	public $ticketState = array(
			'0'=>'正常',
			'1'=>'预售',
			'2'=>'热卖'
	);
/**
 * Components
 *
 * @var array
 */
	public $components = array('Paginator');
	
	public function beforeFilter(){
		parent::beforeFilter();
		$this->Auth->allow('index','view','nav');
	}

	public function index(){
		$SITEID = Configure::read('SITEID');
		$this->request->named = parseSeoParam($this->request->params['pass']);
		//pr($this->request->params);
		$cate_id = isset($this->request->params['cate'])?$this->request->params['cate']:false;
		
		if(isset($this->request->params['scate']))$this->request->named['scate'] = $this->request->params['scate'];
		if($cate_id == 11){
			$son_cates = $this->Ticket->TicketCate->findTicketCateList(11);
		}else{
			$son_cates = array();
		}
		
		$conditions = $this->indexSearch();
			
		$this->Paginator->settings = array(
			'conditions'=>	$conditions['conditions'],
			'order'=>$conditions['order'],
			'limit'=>20		
		);
		$this->Ticket->unbindModel(array(
				'hasMany'=>array('TicketAdvisory'),
				'belongsTo'=>array('SysWebsite','SysSeo','ViewPhoto','TicketCate','TicketScate')
		),true);
		$tickets = $this->Paginator->paginate('Ticket');
		
		$venues = $this->Ticket->Venue->getSiteEnableVenue($SITEID);

		$this->set('cate_id',$cate_id);
		$this->set('son_cates',$son_cates);
		$this->set('venues',$venues);
		
		$this->set('tickets',$tickets);
		
		// 分类-------------------------------------------------------------
		$this->loadModel('TicketCate');
		$siteTicketCate = $this->TicketCate->getSiteEnable($SITEID);
		$this->set('siteTicketCate',$siteTicketCate);
		
		// 最新看点-------------------------------------------------------------
		$this->loadModel('Article');
		$newArticles = $this->Article->find('all',array(
				'conditions'=>array(
					'Article.article_cate_id <>'=>2,
			        'Article.enable'=>1
				),
				'limit'=>7,
				'order'=>'Article.publish DESC'
		));
		$this->set('newArticles',$newArticles);
		
		// 热门活动-------------------------------------------------------------
		$hotArticles = $this->Article->find('all',array(
				'conditions'=>array(
						'Article.article_cate_id'=>2,
				        'Article.enable'=>1
				    
				),
				'limit'=>7,
				'order'=>'Article.publish DESC'
		));
		$this->set('hotArticles',$hotArticles);
		
		$seo_title = array();
		foreach ($conditions['select'] as $sk=>$sv){
			if($sv){
				
				if($sk == 'key'){
					$seo_title[-1]=$sv;
				}
				if($sk == 'cate'){
					$fc = $this->Ticket->TicketCate->findById($sv);
					if($sv == 11){
						$seo_title['z']=$fc['TicketCate']['title_zh'];
					}else{
						$seo_title['a']=$fc['TicketCate']['title_zh'];
					}
				}
				if($sk == 'scate' && !empty($son_cates)){
					$sb = $this->Ticket->TicketCate->findById($sv);
					$seo_title['b']=$son_cates[$sv];
					
				}
				if($sk == 'venue' && !empty($venues)){
					$seo_title['c']=$venues[$sv];
				}
				if($sk == 'show'){
					if($sv == 1){
						$seo_title['d']='今天';
					}else if($sv == 2){
						$seo_title['d']='明天';
					}else if($sv == 3){
						$seo_title['d']='一周内';
					}else if($sv == 4){
						$seo_title['d']='一个月内';
					}else{
						$seo_title['d']=$sv;
					}
				}
				if($sk == 'price'){
					if($sv == 1){
						$seo_title['e']='100元以下';
					}else if($sv == 2){
						$seo_title['e']='101-300元';
					}else if($sv == 3){
						$seo_title['e']='301-500元';
					}else if($sv == 4){
						$seo_title['e']='500元以上';
					}else{
				
					}
				}
				
			}
		}
		$seo_keywords = false;
		$seo_description = false;
		$seo_ext = '门票预订【秦文票务】';
		if(!empty($seo_title)){
			if(count($seo_title) == 1 && (isset($seo_title['a'])||isset($seo_title['z']))){ //一级
				$seo_title		 = $fc['SysSeo']['title'];
				$seo_keywords	 = $fc['SysSeo']['keywords'];
				$seo_description = $fc['SysSeo']['description'];
			}else if(count($seo_title) == 2 && isset($fc) && isset($sb)){
				$seo_title		 = $sb['SysSeo']['title'];
				$seo_keywords	 = $sb['SysSeo']['keywords'];
				$seo_description = $sb['SysSeo']['description'];
			}else if(count($seo_title) == 1 && (isset($seo_title[-1]))){
				$seo_title		 = $seo_title[-1];
				$seo_ext = '【秦文票务演出订票官网】';
			}else{
				ksort($seo_title);
				$seo_title = join('_',$seo_title);
			}
		}else{
			if(isset($fc)){
				$seo_title		 = $fc['SysSeo']['title']; 
				$seo_keywords	 = $fc['SysSeo']['keywords'];
				$seo_description = $fc['SysSeo']['description'];
			}else{
				$seo_title = false;
			}
		};
		if($seo_title){
			$this->set('seo_title',$seo_title);
			$this->set('seo_keywords',$seo_keywords);
			$this->set('seo_description',$seo_description);
			$this->set('seo_title_ext',$seo_ext);
		}
	}
	
	private function indexSearch(){
		$cate = isset($this->request->params['cate'])?$this->request->params['cate']:false;
		$venue = isset($this->request->named['venue'])?$this->request->named['venue']:false;
		$scate = isset($this->request->named['scate'])?$this->request->named['scate']:false;
		$show = isset($this->request->named['show'])?$this->request->named['show']:false;
		$price = isset($this->request->named['price'])?$this->request->named['price']:false;
		$order = isset($this->request->named['sort'])?$this->request->named['sort']:false;
		$key = isset($this->request->query['key'])?$this->request->query['key']:false;
		if(!$key){
			$key = isset($this->request->named['key'])?$this->request->named['key']:false;
		}
		
		$conditions = array();
		$conditions['Ticket.enable'] = 1;
		if($key){
			$this->loadModel('SysSearch');
			$ids = $this->SysSearch->search($key);
			if(!empty($ids['ids'])){
				$conditions['Ticket.id'] = $ids['ids'];
				$this->set('key',$key);
				$this->set('rsword',$ids['sword']);
			}else{
				$conditions['Ticket.id'] = false;
				$this->set('key',$key);
			}
		}
		
		if($scate){
			$conditions['Ticket.ticket_scate_id'] = $scate;
		}else if($cate){
			$conditions['Ticket.ticket_cate_id'] = $cate;
		}
		
		if($venue){
			$conditions['Ticket.venue_id'] = $venue;
		}
		if($show){
			if($show == 1){
				$conditions['Ticket.showtime'] = date('Y-m-d');
			}else if($show == 2){
				$conditions['Ticket.showtime'] = date('Y-m-d',strtotime("+1 day"));
			}else if($show == 3){
				$conditions['Ticket.showtime >='] = date('Y-m-d');
				$conditions['Ticket.showtime <='] = date('Y-m-d',strtotime("+7 day"));
			}else if($show == 4){
				$conditions['Ticket.showtime >='] = date('Y-m-d');
				$conditions['Ticket.showtime <='] = date('Y-m-d',strtotime("+30 day"));
			}else{
				$conditions['Ticket.showtime'] =  $show;
			}
		}
		if($price){
			if($price == 1){
				$conditions['Ticket.price_min <='] = 100;
			}else if($price == 2){
				$conditions['Ticket.price_min <='] = 300;
				$conditions['Ticket.price_min >'] = 100;
			}else if($price == 3){
				$conditions['Ticket.price_min <='] = 500;
				$conditions['Ticket.price_min >'] = 300;
			}else if($price == 4){
				$conditions['Ticket.price_max >'] = 500;
			}
		}
		
		if($order){
			if($order == 'new'){
				$sort = 'Ticket.created DESC';
			}else if($order == 'ing'){
				$sort = 'Ticket.showtime DESC';
			}
		}else{
			$sort = 'Ticket.created DESC';
		}
		
		$sparams = array('cate'.$cate,'scate'.$scate,'venue'.$venue,'show'.$show,'price'.$price,'sort'.$order,'key'.$key);
		$sel = array('cate'=>$cate,'scate'=>$scate,'venue'=>$venue,'show'=>$show,'price'=>$price,'sort'=>$order,'key'=>$key);
		$this->set('sparams',$sparams);
		return array('conditions'=>$conditions,'order'=>$sort,'select'=>$sel);
	}
	
	/**
	 * 票品导航
	 * @author mingxing.zhao@qq.com
	 * @date 2014-3-16 下午12:35:58
	 * @param variable
	 * @return 
	 */
	public function nav(){
		$SITEID = Configure::read('SITEID');
		$siteTicketCate = $this->Ticket->TicketCate->getSiteEnable($SITEID);
		$this->set('siteTicketCate',$siteTicketCate);
		
		$tickets = array();
		foreach ($siteTicketCate as $tk=>$tc) {
			$tickets[$tk]=$this->Ticket->find('all',array(
					'conditions' => array(
						'OR'=>array(
							'Ticket.ticket_cate_id'=>$tk,
							'Ticket.ticket_scate_id'=>$tk,
						),
					    'Ticket.enable'=>1,
						'Ticket.date_end >'=>date('Y-m-d')
					),
					'order' => 'Ticket.date_end DESC,Ticket.sort_top DESC,Ticket.showtime DESC',
					//'limit' => 20,
			));
		}
		$this->set('tickets',$tickets);
		$this->set('seo_title','陕西最新演出门票大全');
		$this->set('seo_keywords','陕西最新演出门票');
		$this->set('seo_description','陕西最新演出门票大全包括：演唱会门票、音乐会门票、话剧门票、儿童演出门票、舞蹈芭蕾门票、体育赛事门票预订等。秦文票务订票电话：4000978006。');
		$this->set('seo_title_ext','【秦文票务演出订票官网】');
	}
	
	/**
	 * 最近浏览
	 * @author mingxing.zhao@qq.com
	 * @date 2014-3-16 下午12:36:24
	 * @param variable
	 * @return 
	 */
	public function recent($ticket = false){
// 		$this->Session->delete('RecentTicket');
// 		$this->Session->delete('RecentTicketIndex');
		$checker = $this->Session->check('RecentTicket');
		$recent = array();
		if($ticket){
			$checkerRti = $this->Session->check('RecentTicketIndex');
			if($checkerRti){
				$Rti = $this->Session->read('RecentTicketIndex');
				if(in_array($ticket['Ticket']['id'],$Rti)){
					return $this->Session->read('RecentTicket');
				}else{
					$Rti[] = $ticket['Ticket']['id'];
					$this->Session->write('RecentTicketIndex',$Rti);
				}
			}else{
				$Rti[] = $ticket['Ticket']['id'];
				$this->Session->write('RecentTicketIndex',$Rti);
			}
			if($checker){
				$recent = $this->Session->read('RecentTicket');
				$recent[] = $ticket;
				$this->Session->write('RecentTicket',$recent);
			}else{
				$recent[] = $ticket;
				$this->Session->write('RecentTicket',$recent);
			}
		}else{
			if($checker){
				$recent = $this->Session->read('RecentTicket');
			}else{
				$recent[] = $ticket;
				$this->Session->write('RecentTicket',$recent);
			}
		}
	} 
	
	/**
	 * 票品详情
	 * @author mingxing.zhao@qq.com
	 * @date 2014-1-8 下午8:52:44
	 * @param variable
	 * @return 
	 */
	public function view($id = null) {
		if (!$this->Ticket->exists($id)) {
			throw new NotFoundException(__('Invalid ticket'));
		}
		$options = array('conditions' => array('Ticket.' . $this->Ticket->primaryKey => $id));
		$ticket = $this->Ticket->find('first', $options);
		if ($ticket['Ticket']['enable'] !=1) {
		    throw new NotFoundException(__('Invalid ticket'));
		}
		$count = $ticket['Ticket']['count']+1;
		$ca = array(
				'Ticket'=>array(
						'id'=>$id,
						'count'=>$count
				)
		);
		$this->Ticket->save($ca);

		//--------------------------------
		if($ticket['Ticket']['spt_seat']){
			$this->loadModel('Seat.TicketShowing');
			$TicketShowings = $this->TicketShowing->getShowingByTikcetId($id);
			$this->set('TicketShowings',$TicketShowings);
		}
		
		
		//pr($ticket);
		$seo_title = array();
		$seo_title[] = $ticket['Ticket']['title'];
// 		if($ticket['TicketScate']['id']>0){
// 			$seo_title[] = $ticket['TicketScate']['title_zh'];
// 		}
// 		$seo_title[] = $ticket['TicketCate']['title_zh'];
		
		$this->set('seo_title',join('_',$seo_title));
		$this->set('seo_title_ext','门票_订票【秦文票务】');
		
		$seo_keywords	 = $ticket['SysSeo']['keywords'];
		$seo_description = $ticket['SysSeo']['description'];
		$this->set('seo_keywords',$seo_keywords);
		$this->set('seo_description',$seo_description);
		
		$this->recent($ticket);
		$this->set('ticket', $ticket);
		
		$relateTicket = $this->Ticket->relateTicket($ticket['Ticket']['tags'],5,$ticket['Ticket']['id']);
		$this->set('relateTicket',$relateTicket);
		
		$this->loadModel('Article');
		$relateArticle = $this->Article->relateArticle($ticket['Ticket']['tags'],5);
		$this->set('relateArticle',$relateArticle);
		
		$newArticle = $this->Article->newArticle(6);
		$this->set('newArticle',$newArticle);
		
		$tuijian = $this->Ticket->recommendTicket(6);
		$this->set('tuijianT',$tuijian);
		
		$newTicket = $this->Ticket->newTicket(6);
		$this->set('newTicket',$newTicket);
		
		// 票品分类-------------------------------------------------------------
		$SITEID = 1;
		$this->loadModel('TicketCate');
		$siteTicketCate = $this->TicketCate->getSiteEnable($SITEID);
		$this->set('siteTicketCate',$siteTicketCate);
	}
/**
 * admin_index method
 *
 * @return void
 */
	public function admin_index() {
		$this->Ticket->recursive = 0;
		$action = array('admin' => true,'controller' => 'Tickets','action'=>'jsonPage');
		$param = $this->Ticket->pageParam($action);
		$this->set('paginationScript',$this->Ticket->showGridPagination($param));
	}
	
	/**
	 * function
	 * @author mingxing.zhao@qq.com
	 * @date 2013-12-21 下午5:05:53
	 * @param variable
	 * @return
	 */
	function admin_jsonPage($type = false){
		$this->Ticket->recursive = 0;
		$this->autoRender = false;
		$searchtype = $this->request->data('_search');
		$conditions = array();
		if($searchtype=='true'){
			$conditions = $this->search_condition($this->request->data);
		}

		$conditions['Ticket.enable'] = 1;
		$conditions['Ticket.sys_website_id']= $this->Session->read('SITEID');
	
		$config = array(
				'_search'=>$searchtype,
				'page'=>$this->request->data('page'),
				'rows'=>$this->request->data('rows'),
				'sidx'=>$this->request->data('sidx'),
				'sord'=>$this->request->data('sord')
		);
		$res = $this->Ticket->pagination($config,array(),$conditions);
		return $this->Ticket->jsonData($res);
	}
	/**
	 * 查询条件
	 * @author zmx@gootop.net
	 * @Date 2011-2-23
	 * @return
	 */
	private function search_condition($param){
		$search['Ticket'] = $param['Ticket'];
		$c = $this->postConditions($search);
		$return = array();
		if($c['Ticket.id']){
			$return['Ticket.id'] = $c['Ticket.id'];
		}else if($c['Ticket.title']){
			$return['Ticket.title like'] = '%'.$c['Ticket.title'].'%';
		}
		return $return;
	}

/**
 * admin_view method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function admin_view($id = null) {
		if (!$this->Ticket->exists($id)) {
			throw new NotFoundException(__('Invalid ticket'));
		}
		$options = array('conditions' => array('Ticket.' . $this->Ticket->primaryKey => $id));
		$this->set('ticket', $this->Ticket->find('first', $options));
	}

/**
 * admin_add method
 *
 * @return void
 */
	public function admin_add() {
		$ticketCates = $this->Ticket->TicketCate->getSiteREnable($this->Session->read('SITEID'));
		if ($this->request->is('post')) {
			$this->Ticket->create();
			if ($this->Ticket->save($this->request->data)) {
				$this->Session->setFlash(__('票品添加成功'),'tip/tip_float',array('t'=>'success'));
				return $this->redirect(array('action' => 'index'));
			} else {
				if($this->request->data['Ticket']['list_photo_id']){
					$photo = $this->Ticket->ListPhoto->findById($this->request->data['Ticket']['list_photo_id']);
					$this->request->data['ListPhoto'] = $photo['ListPhoto'];
				}
				if($this->request->data['Ticket']['view_photo_id']){
					$photo = $this->Ticket->ViewPhoto->findById($this->request->data['Ticket']['view_photo_id']);
					$this->request->data['ViewPhoto'] = $photo['ViewPhoto'];
				}
				$this->Session->setFlash(__('票品添加失败，请重试'),'tip/tip_float');
			}
		}else{
			$def=array_keys($ticketCates);
			$this->request->data['Ticket']['ticket_cate_id'] = $def[0];
		}
		$ticketScates = $this->Ticket->TicketScate->findTicketCateList($this->request->data['Ticket']['ticket_cate_id']);
		$venues = $this->Ticket->Venue->getSiteEnableVenue($this->Session->read('SITEID'));
		$ticketconner = $this->ticketState;
		$this->set(compact('ticketCates','ticketScates', 'venues','ticketconner'));
	}

/**
 * admin_edit method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function admin_edit($id = null) {
		if (!$this->Ticket->exists($id)) {
			throw new NotFoundException(__('Invalid ticket'));
		}
		if ($this->request->is(array('post', 'put'))) {
			if ($this->Ticket->save($this->request->data)) {
				$this->Session->setFlash(__('票品修改成功'),'tip/tip_float',array('t'=>'success'));
				return $this->redirect(array('action' => 'index'));
			} else {
				if($this->request->data['Ticket']['list_photo_id']){
					$photo = $this->Ticket->ListPhoto->findById($this->request->data['Ticket']['list_photo_id']);
					$this->request->data['ListPhoto'] = $photo['ListPhoto'];
				}
				if($this->request->data['Ticket']['view_photo_id']){
					$photo = $this->Ticket->ViewPhoto->findById($this->request->data['Ticket']['view_photo_id']);
					$this->request->data['ViewPhoto'] = $photo['ViewPhoto'];
				}
				$this->Session->setFlash(__('票品添加失败，请重试'),'tip/tip_float');
			}
		} else {
			$options = array('conditions' => array('Ticket.' . $this->Ticket->primaryKey => $id));
			$this->request->data = $this->Ticket->find('first', $options);
		}
		$ticketCates = $this->Ticket->TicketCate->getSiteREnable($this->request->data['Ticket']['sys_website_id']);
		$ticketScates = $this->Ticket->TicketScate->findTicketCateList($this->request->data['Ticket']['ticket_cate_id']);
		$venues = $this->Ticket->Venue->getSiteEnableVenue($this->request->data['Ticket']['sys_website_id']);
		$ticketconner = $this->ticketState;
		$this->set(compact('ticketCates','ticketScates', 'venues','ticketconner'));
	}

/**
 * admin_delete method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function admin_delete($id = null) {
		$this->Ticket->id = $id;
		if (!$this->Ticket->exists()) {
			throw new NotFoundException(__('Invalid ticket'));
		}
		$this->request->onlyAllow('post', 'delete');
		if ($this->Ticket->delete()) {
			$this->Session->setFlash(__('The ticket has been deleted.'));
		} else {
			$this->Session->setFlash(__('The ticket could not be deleted. Please, try again.'));
		}
		return $this->redirect(array('action' => 'index'));
	}
	
	public function admin_close($id = null) {
		$this->Ticket->id = $id;
		if (!$this->Ticket->exists()) {
			throw new NotFoundException(__('Invalid ticket'));
		}
		//$this->request->onlyAllow('post', 'delete');
		$this->Ticket->set('enable',2);
		if ($this->Ticket->save()) {
			$this->Session->setFlash(__('The ticket has been deleted.'),'tip/tip_float',array('t'=>'success'));
		} else {
			$this->Session->setFlash(__('The ticket could not be deleted. Please, try again.'),'tip/tip_float');
		}
		return $this->redirect(array('action' => 'index'));
	}
}
